import { Toast } from 'antd-mobile'
import axios from 'axios'

import {
  getTokenInfo,

  // ,removeTokenInfo
} from './storage'
const baseURL = 'http://geek.itheima.net/v1_0'
const instance = axios.create({
  timeout: 5000,
  baseURL,
})

//配置请求拦截器
instance.interceptors.request.use(
  (config) => {
    //对config做点什么
    //获取token
    const token = getTokenInfo().token
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    //对error做点什么
    return Promise.reject(error)
  }
)

//响应拦截器
instance.interceptors.response.use(
  (response) => {
    //对响应做点什么
    return response.data
  },
  async (err) => {
    //对error做点什么
    if (!err.response) {
      //网络原因
      Toast.show({
        icon: 'fail',
        content: '网络繁忙',
      })
      return Promise.reject(err)
    }
    //如果网络没问题
    if (err.response.status !== 401) {
      Toast.show({
        icon: 'fail',
        content: err.response.data.message,
      })
      return Promise.reject(err)
    }
    //如果网络没问题，且是401token失效的问题
  }
)

export default instance
